var user = {
  getId: function() {
    if (this.id) {
      return this.id;
    } else {
      const KEY_USER_ID = 'x-user-id';
      this.id = localStorage.getItem(KEY_USER_ID);
      if (!this.id) {
        this.id = new Date().getTime() + '' + Math.floor(Math.random() * 10);
        localStorage.setItem(KEY_USER_ID, this.id);
      }
        return this.id;
    }
  },
  getVisitorId: function() {
    const KEY_VISITOR_ID = 'x-user-visitor-id';
    if (this.visitorId && this.visitorId != null) {
      localStorage.setItem(KEY_USER_ID, this.id);
      return this.visitorId;
    } else {
      this.visitorId = localStorage.getItem(KEY_VISITOR_ID);
      if (this.visitorId && this.visitorId != null) {
          return this.visitorId;
      } else {
          return this.getId();
      }
    }
  }
}

//
const fpPromise = new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.onload = resolve
  script.onerror = reject
  script.async = true
  script.src = 'https://cdn.jsdelivr.net/npm/@fingerprintjs/fingerprintjs@3/dist/fp.min.js'
  document.head.appendChild(script)
}).then(() => FingerprintJS.load());

var http = {

  request: function(url, body) {
    var query = {
      url: url + ((url.indexOf('?') !== -1) ? '&' : '?') + 'timestamp=' + new Date().getTime(),
      method: 'post',
      withCredentials: true,
      timeout: 900000,
      headers: { 'Request-Ajax': true, 'x-requested-with': 'XMLHttpRequest', 'X-USER-ID': user.getId(), 'X-VISITOR-ID': user.getVisitorId() }
    }
    query.data = body;

    return axios.request(query).then(
      resp => {
        return new Promise((resolve, reject) => {
          if (axios.isCancel(resp)) {
            return;
          }
          if (!resp.data) {
            reject(new Error('服务器响应超时'));
            return;
          }
          if (resp.data.status === 401) {
            console.log("无权限");
          } else if (resp.data.status === 400) {
            console.log("无效请求");
          } else if (resp.data.status === 0) {
            resolve(resp.data.data);
          } else {
            resp.data.message = resp.data.msg;
            reject(resp.data);
          }
        });
      },
      e => {
        return Promise.reject(e.response);
      }
    ).catch(e => {
        if (e.status === 504) {
            console.log("服务器响应超时");
        }
        return Promise.reject(e.statusText);
    });
  }
}
